<template>
<q-page padding>
  <q-btn flat color="primary" @click="draw()" label="刷新可视化" />
  <div id="echart" class="echart" style="width:70vw; height:70vh"></div>
</q-page>
</template>

<script>
import {
  mapState
} from 'vuex'
import echarts from 'echarts'
import {ConsumerSegmentPlot} from 'assets/vplots'

export default {
  name: 'VdataPlot',
  data () {
    return {
      obj: null,
      cache: null,
      chart: {},
      plot: {}
    }
  },
  mounted () {
    this.loadFromDB(this.objUrl, this.loadObj)
    this.loadFromDB(this.cacheUrl, this.loadCache)
  },
  beforeDestroy: function () {
    this.plot.removeBackmatter(this.chart)
  },
  computed: {
    ...mapState('subtoken', [
      'token'
    ]),
    objUrl () {
      return 'vdatas/' + this.itemId
    },
    cacheUrl () {
      return (
        'vcaches/?where={"f_id":"' + this.itemId + '"}'
        // + '&projection={"heatmap_image":1}'
      )
    },
    itemId () {
      return this.$route.params.itemId
    },
    loaded () {
      return this.obj && this.cache
    }
  },
  methods: {
    loadFromDB (url, func) {
      this.$axios.get(
        this.$store.state.api.apiRoot + url)
        .then(
          (response) => {
            func(response)
          })
        .catch(
          (error) => {
            console.log(error)
          })
    },
    loadObj (response) {
      this.obj = response.data
    },
    loadCache (response) {
      if (response.data._items.length > 0) {
        this.cache = response.data._items[0]
      }
    },
    draw () {
      // init echart
      const echartNode = this.$el.getElementsByClassName('echart')[0]
      this.chart = echarts.init(echartNode)
      this.plot = new ConsumerSegmentPlot()
      // generate option object with ConsumerSegmentPlot in @/assets/vplots
      const option = this.plot.genOption({
        data: this.obj.data, // core data for tooltips, scatter chart and axes
        cache: this.cache.cache // image data for red-blue heatmap chart
      })
      // set option
      this.chart.setOption(option)
      // add event handlers to refresh bolders and heatmap image when resize
      this.plot.addBackmatter(this.chart, this.cache.cache)
    }
  },
  watch: {
    loaded: function (new_, old_) {
      if (new_ === null) {
        return
      }
      this.draw()
    },
    token: function (new_, old_) {
      if (new_ === '') {
        this.obj = null
        this.cache = null
        return
      }
      this.loadFromDB(this.objUrl, this.loadObj)
      this.loadFromDB(this.cacheUrl, this.loadCache)
    }
  }

}
</script>

<style scoped>
</style>
